/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.scalia.meteocal.control;

import com.scalia.meteocal.entity.Event;
import com.scalia.meteocal.weather.ForecastProvider;
import com.scalia.meteocal.weather.StubForecastProvider;
import com.scalia.meteocal.weather.WeatherForecast;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author gabriele
 */
@Singleton
public class ForecastUpdater {

    @EJB
    EventManager eventManager;
    
    @EJB
    NotificationManager notificationManager;
    
    @PersistenceContext
    EntityManager em;
    
    ForecastProvider forecastProvider = new StubForecastProvider();
    
    @Schedule(second="0", minute="*", hour="*") //each minute
    protected void scheduleForecastUpdate() {
        List<Event> events = eventManager.getAllEvents();
        Date now = new Date();
        for (Event event : events) {
            if (event.getForecastTemperature() == null) {
                WeatherForecast weatherForecast = forecastProvider.getForecast(event.getCity(), event.getStartTime());
                if (weatherForecast == null) {
                    continue;
                }
                event.setForecastTemperature(weatherForecast.getTemperature());
                event.setWeatherTypeForecast(weatherForecast.getWeatherType().getName());
                em.merge(event);
            }
        }
    }

    @Schedule(second = "0,10,20,30,40,50", minute = "*", hour = "*") //each 10 seconds
    protected void checkForBadweatherConditions() {
        List<Event> events = eventManager.getAllEvents();
        Date now = new Date();
        for (Event event : events) {
            if (event.isOutdoor() && now.before(event.getStartTime()) && ((event.getStartTime().getTime() - now.getTime()) < (1000 * 60 * 60 * 24)) && !event.isNotificated()) {
                event.setNotificated(true);
                em.merge(event);
                //check for bad weather condition
                if ((event.getMinTemperature() != null && event.getMinTemperature() > event.getForecastTemperature())
                        || (event.getMaxTemperature() != null && event.getMaxTemperature() < event.getForecastTemperature())
                        || Arrays.asList(eventManager.getBadWeatherTypes(event.getBadWeatherTypes())).contains(eventManager.getBadWeatherType(event.getWeatherTypeForecast()))) {
                    notificationManager.badWeatherForOutdoorEvent(event);
                }
            }
        }
    }
}
